package com.commons.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.annotation.RequirePerms;
import com.woniuxy.service.UserService;
import com.woniuxy.utils.JWTUtil;
import com.woniuxy.utils.ResponseResult;
import com.woniuxy.utils.ResultStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class PermsInterceptor extends HandlerInterceptorAdapter {

    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.查看当前被请求的方法上是否有指定的注解，有则获取到注解中的值
        //判断当前请求是否请求的controller中的方法
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获取被调用的方法
            Method method = handlerMethod.getMethod();
            //判断是否有注解
            if (method.isAnnotationPresent(RequirePerms.class)) {
                //有注解
                RequirePerms requirePerms = method.getDeclaredAnnotation(RequirePerms.class);
                //获取权限信息
                String perms = requirePerms.value();
                //2.获取token得到用户的信息
                String uname = JWTUtil.getUname(request.getHeader("authentication"));
                //3.通过用户信息得到所有权限信息，再与当前方法上的权限对比
                //调用service
                if (userService.hasPerms(uname,perms).getStatus()== ResultStatus.HAVE_PERMS) {
                    return true;
                }
                //否则没权限，结束请求，返回没权限的结果
                ResponseResult result = new ResponseResult(500, ResultStatus.NO_PERMS,"没权限", null);
                String data = new ObjectMapper().writeValueAsString(result);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(data);
                //结束请求
                return false;
            }
        }
        return true;
    }
}
